<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        *{margin: 0;padding: 0;}
        html,body{height: 100%;background-color: #000;}
        .blood1{
            width: 500px;height: 30px;background-color: greenyellow;
            border: 5px solid white;
            position: relative;
            overflow: hidden;
        }
        .blood2{
            width: 500px;height: 30px;background-color: red;
            position: absolute;
        }
    </style>
</head>
<body>
    <div class="blood1">
        <span class="blood2"></span>
    </div>
    
</body>

<script>

    //封装 随机[min，max)的整数 函数
    function starSize(max,min){
        return parseInt(Math.random()*(max-min+1)+min);
    }

    //封装 获取元素非行内样式 函数
    function getStyle(ele,attr){
        if(window.getComputedStyle){
            return getComputedStyle(ele,false)[attr];
        }else{
            return ele.currentStyle[attr];
        }
    }

    var spanObj;
    var spanWidth;
    var timer1;
    var timer2;
    timer1 = setInterval(function(){
        spanObj = document.querySelector('.blood2');
        spanWidth = getStyle(spanObj,'width').slice(0,-2);
        spanWidth-=5;
        spanObj.style.width = spanWidth + 'px';
        if(spanWidth < 0){
            alert('GAME OVER')
            clearInterval(timer1);
            clearInterval(timer2);
        }

    },50)

    

    //网页【间隔1s】随机出现一个小星星
    timer2 = setInterval(function(){
        var imgObj = document.createElement('img');
        imgObj.src = './img/star.gif';
        imgObj.width = starSize(50,30);
        imgObj.height = starSize(50,30);
        // 随机位置：0~(网页可见视口宽度-img宽度)
        imgObj.style.position = 'absolute';
        var maxLeft = (window.innerWidth || document.documentElement.clientWidth) - imgObj.width;
        imgObj.style.left = starSize(maxLeft,0) + 'px'
        var maxTop = (window.innerHeight || document.documentElement.clientHeight) - imgObj.height;
        imgObj.style.top = starSize(maxTop,0) + 'px';
        document.body.appendChild(imgObj);

    },500)

    //单击小星星给它删除
    document.body.onclick = function(evt){
        var e = evt || window.event;
        var target = e.target || e.srcElement
        if(target.nodeName == 'IMG'){
            document.body.removeChild(target);
            spanObj.style.width = (spanWidth + 50) + 'px';
        }

    }
    


</script>
</html>